<!-- 订单信息同步页 -->
<template>
  <div class="order-sync">
    <!-- 查询表单 -->
    <el-form class="demo-form-inline" ref="formRef" :model="queryForm" label-width="100px" size="small" inline>
      <el-form-item label="工单编号" prop="orderId">
        <el-input v-model="queryForm.orderId" placeholder="工单编号" clearable></el-input>
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="queryForm.customerName" placeholder="客户名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="客户经理名称" prop="managerName">
        <el-input v-model="queryForm.managerName" placeholder="客户经理名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="fetchData">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-refresh" @click="resetData">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="el-row">
      <el-button type="info" icon="el-icon-coin" plain size="small" @click="syncData">数据同步</el-button>
      <el-button type="success" icon="el-icon-plus" plain size="small" @click="handleAdd">新增</el-button>
      <el-button type="danger" icon="el-icon-delete" plain size="small" :disabled="selectedRows.length === 0" @click="handleBatchDelete">批量退订</el-button>
    </div>

    <!-- 表格 -->
    <el-table
      :data="tableData"
      height="100%"
      style="width: 100%; "
      @selection-change="handleSelectionChange"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55" fixed></el-table-column>
      <el-table-column type="index" label="序号" width="50" fixed></el-table-column>
      <el-table-column prop="orderId" label="工单编号" width="120" fixed></el-table-column>
      <el-table-column prop="contractYears" label="合同年限" width="100"></el-table-column>
      <el-table-column prop="unit" label="单位" width="100"></el-table-column>
      <el-table-column prop="validityPeriod" label="合同有效期" width="150"></el-table-column>
      <el-table-column prop="region" label="地区" width="100"></el-table-column>
      <el-table-column prop="amount" label="合同金额" width="120"></el-table-column>
      <el-table-column prop="productInstanceId" label="专线产品实例标示" width="150"></el-table-column>
      <el-table-column prop="managerName" label="客户经理名称" width="120"></el-table-column>
      <el-table-column prop="managerPhone" label="客户经理联系电话" width="150"></el-table-column>
      <el-table-column prop="lineCount" label="专线数量" width="100"></el-table-column>
      <el-table-column prop="customerName" label="客户名称" width="120"></el-table-column>
      <el-table-column prop="customerPhone" label="客户联系电话" width="150"></el-table-column>
      <el-table-column prop="quantity" label="订购数量/次数/时长" width="180"></el-table-column>
      <el-table-column prop="contractNumber" label="合同编号" width="150"></el-table-column>
      <el-table-column prop="attachmentUrl" label="合同附件地址" width="150"></el-table-column>
      <el-table-column prop="billingMethod" label="计费方式" width="120"></el-table-column>
      <el-table-column prop="effectiveMethod" label="生效方式" width="120"></el-table-column>
      <el-table-column label="操作" width="160" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" @click="handleDetail(scope.row)">详情</el-button>
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">退订</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      background
      style="text-align: right"
    ></el-pagination>

    <!-- 新增/编辑对话框 -->
    <OrderSyncForm
      :visible.sync="dialogVisible"
      :dialogTitle="dialogTitle"
      :formData="form"
      @submit="handleSubmit"
    />

    <!-- 详情对话框 -->
    <OrderSyncDetail
      :visible.sync="detailVisible"
      :formData="selectedRow"
    />
  </div>
</template>

<script>
import OrderSyncForm from './components/OrderSyncForm.vue';
import OrderSyncDetail from './components/OrderSyncDetail.vue';

export default {
  name: "OrderSync",
  components: {OrderSyncForm, OrderSyncDetail},
  data() {
    return {
      queryForm: {
        orderId: "",
        customerName: "",
        managerName: ''
      },
      totalTableData: [],
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: "",
      form: {},
      selectedRows: [],
      loading: false,
      detailVisible: false,
      selectedRow: {}
    };
  },
  methods: {
    syncData() {
      this.loading = true;
      setTimeout(() => {
        // 模拟同步数据
        this.fetchData();
      }, 1000);
    },
    // 生成随机数据
    generateRandomData(count) {
      const units = ["公司A", "公司B", "公司C", "公司D", "公司E"];
      const regions = ["北京", "上海", "广州", "深圳", "杭州"];
      const managerNames = ["张三", "李四", "王五", "赵六", "孙七"];
      const customerNames = ["客户A", "客户B", "客户C", "客户D", "客户E"];
      const billingMethods = ["按次", "按月", "按年"];
      const effectiveMethods = ["立即生效", "次月生效", "次年生效"];

      const data = [];
      for (let i = 0; i < count; i++) {
        const orderId = `OrderNo.00${i + 1}`.slice(-3); // 生成3位订单号
        const contractYears = Math.floor(Math.random() * 5) + 1; // 1到5年的合同期限
        const unit = units[Math.floor(Math.random() * units.length)];
        const validityPeriod = `2023-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1}`; // 随机生成日期
        const region = regions[Math.floor(Math.random() * regions.length)];
        const amount = Math.floor(Math.random() * 100000) + 10000; // 10000到110000之间的金额
        const productInstanceId = `PI${orderId}`;
        const managerName = managerNames[Math.floor(Math.random() * managerNames.length)];
        const managerPhone = `13${Math.floor(Math.random() * 900000000) + 100000000}`; // 随机生成手机号
        const lineCount = Math.floor(Math.random() * 10) + 1; // 1到10的行数
        const customerName = customerNames[Math.floor(Math.random() * customerNames.length)];
        const customerPhone = `13${Math.floor(Math.random() * 900000000) + 100000000}`; // 随机生成手机号
        const quantity = `${Math.floor(Math.random() * 100) + 1}次`; // 1到100次
        const contractNumber = `CN${orderId}`;
        const attachmentUrl = `http://example.com/contract${orderId}.pdf`;
        const billingMethod = billingMethods[Math.floor(Math.random() * billingMethods.length)];
        const effectiveMethod = effectiveMethods[Math.floor(Math.random() * effectiveMethods.length)];

        data.push({orderId, contractYears, unit, validityPeriod, region, amount, productInstanceId, managerName, managerPhone, lineCount, customerName, customerPhone, quantity, contractNumber, attachmentUrl, billingMethod, effectiveMethod});
      }
      return data;
    },
    // 模拟接口请求数据
    fetchData() {
      this.loading = true;
      setTimeout(() => {
        // 生成随机订单数据
        this.totalTableData = this.generateRandomData(Math.random() * 1000);
        // 查询条件
        const {orderId, customerName, managerName} = this.queryForm;
        const filteredData = this.totalTableData.filter(item => {
          return (
            (!orderId || item.orderId.includes(orderId)) &&
            (!customerName || item.customerName.includes(customerName)) &&
            (!managerName || item.managerName.includes(managerName))
          );
        });
        this.total = filteredData.length;
        this.tableData = filteredData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
        this.loading = false;
      }, 1000);
    },
    resetData() {
      this.$refs.formRef.resetFields()
      this.syncData()
    },
    handleAdd() {
      this.dialogTitle = "新增订单";
      this.form = {};
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = "编辑订单";
      this.form = {...row};
      this.dialogVisible = true;
    },
    handleDetail(row) {
      this.selectedRow = row;
      this.detailVisible = true;
    },
    handleDelete(row) {
      this.$confirm('此操作将永久退订该订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.tableData.indexOf(row);
        if (index > -1) {
          this.tableData.splice(index, 1);
        }
        this.$message({
          type: 'success',
          message: '退订成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消退订'
        });
      });
    },
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择要退订的订单!'
        });
        return;
      }
      this.$confirm('此操作将永久退订选中的订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableData = this.tableData.filter(row => !this.selectedRows.includes(row));
        this.$message({
          type: 'success',
          message: '退订成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消退订'
        });
      });
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    handleSubmit(formData) {
      if (this.dialogTitle === "新增订单") {
        this.totalTableData.unshift({...formData});
        this.tableData.unshift({...formData});
      } else {
        const index = this.tableData.findIndex(row => row.orderId === formData.orderId);
        if (index > -1) {
          this.$set(this.tableData, index, {...formData});
        }
      }
      this.dialogVisible = false;
    }
  },
  mounted() {
    // 页面加载时不自动获取数据，等待用户点击同步按钮
  }
};
</script>

<style scoped lang="scss">
.order-sync {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;

  .el-row {
    margin-bottom: 20px;
  }

  .el-table {
    flex: 1；;
    margin-bottom: 20px;
  }
}
</style>
